import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { login, register, logout, getCurrentUser } from '../api/auth'

// 异步登录操作
export const loginUser = createAsyncThunk(
  'auth/login',
  async (credentials, { rejectWithValue }) => {
    try {
      const response = await login(credentials)
      // 保存token到localStorage
      localStorage.setItem('token', response.data.token)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '登录失败' })
    }
  }
)

// 异步注册操作
export const registerUser = createAsyncThunk(
  'auth/register',
  async (userData, { rejectWithValue }) => {
    try {
      const response = await register(userData)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '注册失败' })
    }
  }
)

// 异步获取当前用户信息
export const fetchCurrentUser = createAsyncThunk(
  'auth/fetchCurrentUser',
  async (_, { rejectWithValue }) => {
    try {
      const response = await getCurrentUser()
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '获取用户信息失败' })
    }
  }
)

// 异步登出操作
export const logoutUser = createAsyncThunk(
  'auth/logout',
  async (_, { rejectWithValue }) => {
    try {
      await logout()
      // 清除localStorage中的token
      localStorage.removeItem('token')
      return null
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '登出失败' })
    }
  }
)

const initialState = {
  user: null,
  token: localStorage.getItem('token') || null,
  isAuthenticated: !!localStorage.getItem('token'),
  loading: false,
  error: null,
  permissions: []
}

const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    clearError: (state) => {
      state.error = null
    },
    setPermissions: (state, action) => {
      state.permissions = action.payload
    }
  },
  extraReducers: (builder) => {
    builder
      // 登录状态处理
      .addCase(loginUser.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(loginUser.fulfilled, (state, action) => {
        state.loading = false
        state.user = action.payload.user
        state.token = action.payload.token
        state.isAuthenticated = true
        state.permissions = action.payload.permissions || []
      })
      .addCase(loginUser.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '登录失败'
      })
      // 注册状态处理
      .addCase(registerUser.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(registerUser.fulfilled, (state) => {
        state.loading = false
      })
      .addCase(registerUser.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '注册失败'
      })
      // 获取当前用户信息状态处理
      .addCase(fetchCurrentUser.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchCurrentUser.fulfilled, (state, action) => {
        state.loading = false
        state.user = action.payload
        state.isAuthenticated = true
      })
      .addCase(fetchCurrentUser.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '获取用户信息失败'
        state.isAuthenticated = false
        state.user = null
        state.token = null
        localStorage.removeItem('token')
      })
      // 登出状态处理
      .addCase(logoutUser.fulfilled, (state) => {
        state.user = null
        state.token = null
        state.isAuthenticated = false
        state.permissions = []
      })
  }
})

export const { clearError, setPermissions } = authSlice.actions
export default authSlice.reducer